import random
import time
from tkinter import *
import os


class App(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.number = StringVar()
        self.stopshuffle = False
        self.results = []
        self.createWidgets()

    def createWidgets(self):
        self.label = Label(
            self, text='中奖号码：', font="simhei {}".format(LABELSIZE))
        self.label.pack()
        self.label2 = Label(
            self,
            textvariable=self.number,
            font="Arial {} bold".format(FONTSIZE),
            fg=FONTCOLOUR)
        self.label2.pack()
        self.button = Button(
            self,
            text='开始抽奖',
            command=self.click,
            font="simhei {}".format(LABELSIZE))
        self.button.pack()

    def click(self):
        self.button['text'] = '停止'
        self.button['command'] = self.stop
        self.stopshuffle = False
        self.start(STOP, SLEEP)

    def stop(self):
        self.button['text'] = '开始抽奖'
        self.button['command'] = self.click
        self.stopshuffle = True
        self.appendret(STOP, SLEEP)

    def start(self, stop, sleep):
        while True:
            if not self.stopshuffle:
                self.x = random.randrange(1, stop + 1)
                if len(self.results) == stop - 1:
                    self.number.set("剩余人数不足哦~")
                    break
                elif self.x not in self.results:
                    self.number.set("{:03.0f}".format(self.x))
                else:
                    continue
                self.update()
                time.sleep(sleep)
            else:
                break

    def appendret(self, stop, sleep):
        time.sleep(sleep)
        if len(self.results) < stop - 1:
            self.results.append(self.x)


if __name__ == "__main__":
    configpath = os.path.join(os.path.dirname(__file__), "config.ini")
    f = open(configpath)
    #FONTSIZE = 400
    #STOP = 500
    #SLEEP = 0.05
    config = f.readlines()
    FONTSIZE = int(config[0].split()[0].split("=")[1])
    STOP = int(config[1].split()[0].split("=")[1])
    SLEEP = float(config[2].split()[0].split("=")[1])
    FONTCOLOUR = config[3].split()[0].split("=")[1]
    TITLE = config[4].split()[0].split("=")[1]
    LABELSIZE = int(config[5].split()[0].split("=")[1])
    app = App()
    app.master.title(TITLE)
    app.mainloop()
